﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web.Security;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using com.codebump;

public partial class XTRAC_XTRAC : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.QueryString.HasKeys())
            {
                if (Request.QueryString["listid"] != String.Empty)
                    Session["listid"] = Request.QueryString["listid"];
                else
                    Session["listid"] = 1;


                if (Request.QueryString["dnis"] != null)
                {
                    Session["dnis"] = Request.QueryString["dnis"];
                }
                else
                {
                    Session["dnis"] = "9999999999";
                }
                Session["ani"] = Request.QueryString["ani"];
                Session["servername"] = Request.QueryString["servername"];
                Session["projectname"] = Request.QueryString["projectname"];
                Session["campaignname"] = Request.QueryString["campaignname"];
                Session["agentid"] = Request.QueryString["agentid"];
                Session["agentfirst"] = Request.QueryString["agentfirst"];
                Session["agentlast"] = Request.QueryString["agentlast"];
                Session["commit"] = false;
                Session["CInfo"] = false;
                Session["App"] = new DataAccess();

                Session["leadid"] = Request.QueryString["leadid"];

                if (Convert.ToInt32((string)Session["leadid"]) > 0)
                {
                    Session["IsOutbound"] = true;

                    LoadCustInfo(); // Pre-fill Controls with Customer Info (Loads previous calldata table info based on LeadID, or SubmitLeadInfo if Web Form)

                    // Update CallData Table and committ
                    ((DataAccess)Session["App"]).PutCallData("IsOutbound", "Yes");
                    ((DataAccess)Session["App"]).PutCallData("LeadID", (string)Session["leadid"]);                    
                    ((DataAccess)Session["App"]).CommitCallData();

                    pnlOutboundOpening.Visible = true;
                    pnlInboundOpening.Visible = false;

                }
                else
                {
                    Session["IsOutbound"] = false;
                    tbPhone.Text = Request.QueryString["ani"].Trim();
                    pnlOutboundOpening.Visible = false;
                    pnlInboundOpening.Visible = true;
                }

            }

            //The session variables are requested in the master page currently using the following syntax: Session["servername"] = Request.QueryString["servername"];
            //The page is loaded before the master page so if the code isn't in a control, it will currently error out.
            //((DataAccess)Session["App"]).ConnectInbound(Session["servername"].ToString(), Session["projectname"].ToString(), Session["campaignname"].ToString(), Session["dnis"].ToString(), Session["listid"].ToString());

            WebWizard.ActiveStepIndex = 0;
        }
        else
        {

        }


    }
    //POST LOGIC - For Step or Start pages
    //Add if statements as you add pages
    //For Next and Finish pages it is best to use the index in the if statements as below
    protected void WebWizard_NextButtonClick(object sender, WizardNavigationEventArgs e)
    {
        int page = WebWizard.ActiveStepIndex;
        if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        {
            return;
        }

        if (page == WebWizard.WizardSteps.IndexOf(this.MainOffer))
        {

            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.CollectData)) //post-logic for upsell pages
        {

            return;

        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Recap))
        {
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
            return;
        }
    }

    //POST LOGIC for disposition pages
    //this is for pages that contain a disposition button
    protected void WebWizard_FinishButtonClick(object sender, WizardNavigationEventArgs e)
    {

        int page = WebWizard.ActiveStepIndex;
        if (page == WebWizard.WizardSteps.IndexOf(this.Intro))
        {
            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Recap))
        {

            return;
        }
        if (page == WebWizard.WizardSteps.IndexOf(this.Disposition))
        {
            return;
        }


    }

    //PRE-LOGIC
    //Add if statements as needed for post-logic
    //You can use the Step ID name instead of the index as used in Next and Finish logic.
    protected void WebWizard_ActiveStepChanged(object sender, EventArgs e)
    {
        if (WebWizard.ActiveStep.Title.ToString() == "Recap")
        {

        }
        if (WebWizard.ActiveStep.Title.ToString() == "Disposition")
        {

            if (submitCustData()) // Submit Customer Data before Dispositioning as a Sale
            {            
                pnlDispoConfirm.Visible = false;
                submitOptionalData();
                ((DataAccess)Session["App"]).PutOrderItem(513, 1); // add order to orders table
                ((DataAccess)Session["App"]).CommitOrder();
                ((DataAccess)Session["App"]).PutCallData("webusercode", "01"); // sale disposition
                ((DataAccess)Session["App"]).CommitCallData();
                if (Convert.ToInt32((string)Session["leadid"]) > 0)
                    ((DataAccess)Session["App"]).FinalizeOBLeadSales(); // The FinalizeOBLead() funtion that runs on the DispositonComplete page Load will not work since the Sales Dispositon does not exist in the dtUsercodes table?
                Response.Redirect("../DispositionComplete.aspx");
            }
            else
            {
                WebWizard.ActiveStepIndex = WebWizard.WizardSteps.IndexOf(this.Recap);
            }
            return;
        }
        else
        {
        }

    }

    protected void btnSubmit_Click(object sender, System.EventArgs e)
    {
        bool bReturn = submitCustData();
    }

    protected void btnSearchZip_Click(object sender, EventArgs e)
    {
        ValidateZip(tbZip.Text.ToUpper(), ddlCity, ddlState, ddlCountry);
    }


    protected void ValidateZip(string strZip, DropDownList ddl_City, DropDownList ddl_State, DropDownList ddl_Country)
    {

        ddl_City.Items.Clear();
        ddl_State.Items.Clear();
        ddl_City.Enabled = true;
        ddl_State.Enabled = true;
        if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^\d{5}$)|(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} +\d{1}[A-Z]{1}\d{1}$)"))
        {
            try
            {
                com.codebump.GeoPlaces g = new com.codebump.GeoPlaces();

                com.codebump.AuthenticationHeader authHeader = new com.codebump.AuthenticationHeader();
                authHeader.SessionID = "6JV2ZA4lgG1YRR+HG+JU27QWk9zI3rpRWY2iG2mzNPcdieEQXfQv0OUY0EZ+pOTxhwI1NCuF7b2oY+U/bozy0mhjFHmpaXvb";
                g.AuthenticationHeaderValue = authHeader;

                com.codebump.GeoPlaceDistance[] places = g.GetPlacesInside(strZip, "");

                for (int i = 0; i < places.Length; i++)
                {
                    com.codebump.GeoPlaceDistance place = places[i];
                    ListItem li = new ListItem(place.ToPlace, place.ToState + "," + place.ToPlace);
                    ddl_City.Items.Add(li);
                }

                ddl_State.Items.Add(ddl_City.SelectedItem.Value.Split(",".ToCharArray())[0]);

                //ddlCity.SelectedIndex = 0;

                if (System.Text.RegularExpressions.Regex.IsMatch(strZip.ToUpper(), @"(^[ABCEGHJKLMNPRSTVXY]{1}\d{1}[A-Z]{1} *\d{1}[A-Z]{1}\d{1}$)"))
                {
                    ddl_Country.SelectedValue = "CANADA";
                }
                else
                {
                    ddl_Country.SelectedValue = "USA";
                }

                if (ddl_City.Items.Count <= 0)
                {
                    ddl_City.Items.Add("No Cities Found");
                    ddl_State.Items.Add("No States Found");
                    ddl_City.Enabled = false;
                    ddl_State.Enabled = false;
                }
                else
                {
                    ddl_City.Items.Insert(0, "Select a City");
                    ddl_City.SelectedIndex = 0;
                    ddl_State.Enabled = false;
                }
            }
            catch
            {
                ddl_City.Items.Add("No Cities Found");
                ddl_State.Items.Add("No States Found");
                ddl_City.Enabled = false;
                ddl_State.Enabled = false;
            }
        }
        else
        {
            ddl_City.Items.Add("Invalid Zip");
            ddl_City.Enabled = false;
            ddl_State.Items.Add("Invalid Zip");
            ddl_State.Enabled = false;
        }
    }

    public DataAccess.CardType GetCardType(string cardType)
    {
        switch (cardType)
        {
            case "A":
                return DataAccess.CardType.AmericanExpress;
            case "V":
                return DataAccess.CardType.Visa;
            case "D":
                return DataAccess.CardType.Discover;
            case "M":
                return DataAccess.CardType.MasterCard;
            default:
                return DataAccess.CardType.Visa;
        }
    }



    protected void btnFAQ_Click(object sender, EventArgs e)
    {
        btnFAQ.Text = "View FAQ";
        pnlWizard.Visible = false;

        if (pnlFAQ.Visible)
        {
            pnlFAQ.Visible = false;
            pnlWizard.Visible = true;
        }
        else
        {
            pnlFAQ.Visible = true;
            btnFAQ.Text = "Return to Script";
        }
    }
    #region Validate customer info and write it to in-memory calldata table

    protected bool validateCustomer()
    {
        bool bCustValid = false;

        bCustValid = !(string.IsNullOrEmpty(tbFirstName.Text) ||
            string.IsNullOrEmpty(tbLastName.Text) ||
            string.IsNullOrEmpty(tbAddr.Text) ||
            (tbAddr.Text == "PO BOX ") ||
            string.IsNullOrEmpty(tbZip.Text) ||
            string.IsNullOrEmpty(ddlCity.SelectedItem.Text) ||
            string.IsNullOrEmpty(ddlState.SelectedItem.Text) ||
            string.IsNullOrEmpty(tbPhone.Text) ||
            (tbPhone.Text.Length != 10) ||
            !(System.Text.RegularExpressions.Regex.Match(tbPhone.Text, @"^[1-9]\d{2}[1-9]\d{6}$").Success) ||
            string.IsNullOrEmpty(ddlCountry.SelectedItem.Text)) &&
            (ddlCity.SelectedIndex > 0);

        return bCustValid;
    }

    protected bool submitCustData()
    {
        bool bSubmited = false;
        lblError.Text = "";

        if (validateCustomer())
        {
            ((DataAccess)Session["App"]).PutCallData("firstname", tbFirstName.Text.Replace(",", ""));
            ((DataAccess)Session["App"]).PutCallData("lastname", tbLastName.Text.Replace(",", ""));
            ((DataAccess)Session["App"]).PutCallData("address1", tbAddr.Text.Replace(",", ""));
            if (!string.IsNullOrEmpty(tbAddr2.Text))
                ((DataAccess)Session["App"]).PutCallData("address2", tbAddr2.Text.Replace(",", ""));
            else
                ((DataAccess)Session["App"]).PutCallData("address2", "");
            ((DataAccess)Session["App"]).PutCallData("Zip", tbZip.Text.Replace(",", ""));
            ((DataAccess)Session["App"]).PutCallData("City", ddlCity.SelectedItem.Text.Replace(",", ""));
            ((DataAccess)Session["App"]).PutCallData("State", ddlState.SelectedItem.Text);
            ((DataAccess)Session["App"]).PutCallData("Country", ddlCountry.SelectedItem.Text);
            ((DataAccess)Session["App"]).PutCallData("PrimaryPhone", tbPhone.Text);

            submitOptionalData();
            ((DataAccess)Session["App"]).CommitCallData();

            bSubmited = true;
        }
        //this else covers error checking
        else
        {
            if (tbAddr.Text == "PO BOX ")
            {
                lblError.Text += "Enter a PO BOX number <br/>";
            }
            else
            {
                if (ddlCity.Items.Count > 1 && ddlCity.SelectedIndex == 0)
                {
                    lblError.Text += "Select a City<br/>";
                }
                else
                {
                    lblError.Text += "Enter Valid Customer Data<br/>";
                }
            }
        }
        return bSubmited;
    }
    protected bool submitOptionalData()
    {
        bool bOpt = true;

        //if ((!string.IsNullOrEmpty(tbPhone.Text)) && ((tbPhone.Text.Length != 10) || !(System.Text.RegularExpressions.Regex.Match(tbPhone.Text, @"^[1-9]\d{2}[1-9]\d{6}$").Success)))
        //{
        //    lblError.Text += "Invalid Phone<br/>";
        //    bOpt = false;
        //}
        //else
        //{
        //    if (!string.IsNullOrEmpty(tbPhone.Text))
        //        ((DataAccess)Session["App"]).PutCallData("PrimaryPhone", tbPhone.Text);
        //}

        if ((!string.IsNullOrEmpty(tbEmail.Text)) && !((DataAccess)Session["App"]).IsValidEmail(tbEmail.Text))
        {
            lblError.Text += "Invalid Email<br/>";
            bOpt = false;
        }
        else
        {
            if (!string.IsNullOrEmpty(tbEmail.Text))
                ((DataAccess)Session["App"]).PutCallData("Email", tbEmail.Text);
        }

        return bOpt;
    }
    #endregion Validate customer info and write it to in-memory calldata table

    // Checks for previously entered CallData based on the LeadID, if none, then loads Info from Leads Table
    protected void LoadCustInfo()
    {

        lblLeadID.Text += Convert.ToString(Session["leadid"]);
        tbPhone.Text = Session["ani"].ToString();

        if (((DataAccess)Session["App"]).FillPreviousCallData(Convert.ToString(Session["leadid"])))
        {
            tbAddr.Text = ((DataAccess)Session["App"]).OBGetPreviousCallData("Address1").ToString();
            tbAddr2.Text = ((DataAccess)Session["App"]).OBGetPreviousCallData("Address2").ToString();
            tbZip.Text = ((DataAccess)Session["App"]).OBGetPreviousCallData("Zip").ToString();
            btnSearchZip_Click(null, null);
            ddlCity.SelectedIndex = ddlCity.Items.IndexOf(ddlCity.Items.FindByText(((DataAccess)Session["App"]).OBGetPreviousCallData("City").ToString()));  // Need to programatically assign City after the Search Zip if run                                
            tbFirstName.Text = ((DataAccess)Session["App"]).OBGetPreviousCallData("FirstName").ToString();
            tbLastName.Text = ((DataAccess)Session["App"]).OBGetPreviousCallData("LastName").ToString();
            tbEmail.Text = ((DataAccess)Session["App"]).OBGetPreviousCallData("Email").ToString();

        }
        else
        {
            //Get Lead Info from SubmitLead Table for Web Leads Only
            if (Convert.ToString(Session["dnis"]) == "2144324709")
            {
                GetSubmitLeadData(Convert.ToString(Session["leadid"]))
            }

        }

    }


    protected void  GetSubmitLeadData(string iLeadID)
    {
        System.Data.DataTable dtSubmitLeadData = new System.Data.DataTable("SubmitLeadData");
        SqlConnection ExtSQLConn = new SqlConnection();
        ExtSQLConn.ConnectionString = "Data Source=65.100.157.132; Initial Catalog=SharedPool; User ID = webuser; Password = W3bscript$";

        string SQLSubmitLeadData = "select [65.100.157.132].[VoiceNet_SubmitLead].[dbo].[Leads]" +
                            "where LeadID = '" + HttpContext.Current.Session["leadid"].ToString() + "' ";
        SqlCommand SqlCmdSubmitLeadData = new SqlCommand(SQLSubmitLeadData, ExtSQLConn);
        SqlCmdSubmitLeadData.CommandType = System.Data.CommandType.Text;
        SqlDataAdapter dataAdapterSubmitLeadData = new SqlDataAdapter(SqlCmdSubmitLeadData);

        ExtSQLConn.Open();
        if (ExtSQLConn.State == System.Data.ConnectionState.Open)
        {
            dataAdapterSubmitLeadData.Fill(dtSubmitLeadData);
            if (dtSubmitLeadData.Rows.Count > 0)
            {
                tbZip.Text = Convert.ToString(dtSubmitLeadData.Rows[0]["Zip"]);
                tbFirstName.Text = Convert.ToString(dtSubmitLeadData.Rows[0]["FirstName"]);
                tbEmail.Text = Convert.ToString(dtSubmitLeadData.Rows[0]["Email"]);
            }
            ExtSQLConn.Close();
        }


            
    }


}

